package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper server, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.mapper = server;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //从url中解析引用名称
            String url = request.getUrl();
            Context context =null;
            String appName=null;
            boolean appIsHas =false;
            List<Context> contexts = mapper.getHost().getContexts();
            for (Context c : contexts) {
                if(url.indexOf("/"+ c.getName())==0){//如果斜杠+应用名位于url的首位，则定位应用
                    appIsHas=true;
                    appName= c.getName();
                    context = c;
                    break;
                }
            }
            System.out.println("====是否自定义目录应用："+appIsHas);

            //外置引用的处理
            if(appIsHas){
                //获取路径名称
                String appRequestUrl = url.substring( url.indexOf("/"+appName)+appName.length()+1);
                System.out.println("===外部应用路径："+appRequestUrl);
                Map<String, HttpServlet> httpServletMap = context.getWrapper();
                // 静态资源处理
                if (httpServletMap.get(appRequestUrl) == null) {
                    response.outputHtml(request.getUrl());
                } else {
                    // 动态资源servlet请求：此处需要单独处理下
                    HttpServlet httpServlet = httpServletMap.get(appRequestUrl);
                    System.out.println(httpServlet.getClass().getClassLoader());
                    httpServlet.service(request, response);
                }
            }else {
                // 静态资源处理
                if (servletMap.get(request.getUrl()) == null) {
                    response.outputHtml(request.getUrl());
                } else {
                    // 动态资源servlet请求
                    HttpServlet httpServlet = servletMap.get(request.getUrl());
                    httpServlet.service(request, response);
                }
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }


}
